const { AuditLog, User } = require('../models/db');

const ok = (res, data, extra = {}) => res.json({ success: true, data, ...extra });
const fail = (res, code = 500, message = '服务器错误') => res.status(code).json({ success: false, message, code });

const mapAuditLogToClient = (l) => ({
  id: l._id?.toString(),
  serialNumber: l.serialNumber,
  timestamp: l.timestamp ? new Date(l.timestamp).toISOString() : undefined,
  userId: l.userId || l.user?._id?.toString(),
  username: l.username || l.user?.username,
  userRole: l.user?.role,
  action: l.action,
  module: l.module,
  description: l.description,
  ipAddress: l.ipAddress,
  status: l.status,
  createdAt: l.createdAt ? new Date(l.createdAt).toISOString() : undefined,
});

// 获取序号（递增）
const getNextSerialNumber = async () => {
  const lastRecord = await AuditLog.findOne().sort({ serialNumber: -1 });
  if (!lastRecord || !lastRecord.serialNumber) {
    // 如果没有记录，统计总数+1
    const count = await AuditLog.countDocuments();
    return count + 1;
  }
  return lastRecord.serialNumber + 1;
};

exports.getAllAuditLogs = async (req, res) => {
  try {
    const { page = 1, limit = 20, userId, action, module, username, startDate, endDate, status } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(limit);
    const query = {};
    
    if (userId) query.userId = userId;
    if (action) query.action = action;
    if (module) query.module = module;
    if (username) query.username = new RegExp(username, 'i');
    if (status) query.status = status;
    if (startDate || endDate) {
      query.timestamp = {};
      if (startDate) query.timestamp.$gte = new Date(startDate);
      if (endDate) query.timestamp.$lte = new Date(endDate);
    }
    
    const logs = await AuditLog.find(query)
      .populate('user', 'username role')
      .sort({ timestamp: -1, createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));
    
    const total = await AuditLog.countDocuments(query);
    ok(res, logs.map(mapAuditLogToClient), {
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        totalPages: Math.ceil(total / parseInt(limit))
      }
    });
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.getAuditLogById = async (req, res) => {
  try {
    const l = await AuditLog.findById(req.params.id).populate('user', 'username role email');
    if (!l) return fail(res, 404, '未找到该日志');
    ok(res, mapAuditLogToClient(l));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.createAuditLog = async (req, res) => {
  try {
    const { userId, username, action, module, description, ipAddress, status } = req.body || {};
    if (!action || !module) {
      return fail(res, 400, '缺少必要字段: action | module');
    }
    
    const logData = {
      userId,
      username,
      action,
      module,
      description: description || `${action} - ${module}`,
      ipAddress: ipAddress || req.ip || req.connection.remoteAddress,
      status: status || '成功',
      serialNumber: await getNextSerialNumber(),
      timestamp: new Date()
    };
    
    if (userId) {
      logData.user = userId;
    }
    
    const created = await AuditLog.create(logData);
    ok(res, mapAuditLogToClient(created));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

// 创建审计日志的辅助函数（供其他控制器使用）
exports.createLog = async (userId, username, action, module, description, ipAddress, status = '成功') => {
  try {
    const logData = {
      userId,
      username,
      action,
      module,
      description,
      ipAddress,
      status,
      serialNumber: await getNextSerialNumber(),
      timestamp: new Date()
    };
    
    if (userId) {
      logData.user = userId;
    }
    
    await AuditLog.create(logData);
  } catch (e) {
    console.error('创建审计日志失败:', e);
  }
};

